﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using HF.Framework.DataClientDBAgent;
using HF.WorkFlow.DataContract;
using HF.Framework.SqlDataContract;
using HF.WorkFlow.Const;
namespace HF.WorkFlow.Engine
{
    /// <summary>
    /// 数据访问类OperatorInstance。
    /// </summary>
    public class OperatorInstance
    {
        #region  私有字段
        private SqlDataItem sqlDataItem = new SqlDataItem();
        private string[] fieldList = { "OperatorInstanceId", "WorkFlowId", "WorkTaskId", "WorkFlowInstanceId",
                                         "WorkTaskInstanceId", "UserId", "OperType", "OperRealtion", 
                                         "OperContent", "OperContentText", "OperStatus", "OperDateTime",
                                         "ChangeOperator" };
        private string tableName = "HF_OperatorInstance";
        private string keyField = "OperatorInstanceId";
        private string sqlString = "";

        #endregion

        #region  私有方法
        private void setParameter(OperatorInstanceEntity entity)
        {
            sqlDataItem.ParameterList.Clear();
            sqlDataItem.AppendParameter("@OperatorInstanceId", entity.OperatorInstanceId, typeof(string));
            sqlDataItem.AppendParameter("@WorkFlowId", entity.WorkFlowId, typeof(string));
            sqlDataItem.AppendParameter("@WorkTaskId", entity.WorkTaskId, typeof(string));
            sqlDataItem.AppendParameter("@WorkFlowInstanceId", entity.WorkFlowInstanceId, typeof(string));
            sqlDataItem.AppendParameter("@WorkTaskInstanceId", entity.WorkTaskInstanceId, typeof(string));
            sqlDataItem.AppendParameter("@UserId", entity.UserId, typeof(string));
            sqlDataItem.AppendParameter("@OperType", entity.OperType, typeof(int));
            sqlDataItem.AppendParameter("@OperRealtion", entity.OperRealtion, typeof(int));
            sqlDataItem.AppendParameter("@OperContent", entity.OperContent, typeof(string));
            sqlDataItem.AppendParameter("@OperContentText", entity.OperContentText, typeof(string));
            sqlDataItem.AppendParameter("@OperStatus", entity.OperStatus, typeof(string));
            sqlDataItem.AppendParameter("@OperDateTime", entity.OperDateTime, typeof(DateTime));
            sqlDataItem.AppendParameter("@ChangeOperator", entity.ChangeOperator, typeof(string));
        }

        private void setInsertSql()
        {
            string tmpValueList = "";
            string tmpFieldName = "";
            sqlString = "insert into " + tableName + "(";
            int tmpInt = this.fieldList.Length;
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + ", ";
                tmpValueList = tmpValueList + "@" + tmpFieldName + ",";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName;
            tmpValueList = tmpValueList + "@" + tmpFieldName;
            this.sqlString = sqlString + ")values(" + tmpValueList + ")";
            sqlDataItem.CommandText = sqlString;
        }

        private void setUpdateSql()
        {
            string tmpFieldName = "";
            int tmpInt = this.fieldList.Length;
            sqlString = "update " + tableName + " set ";
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName + ", ";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName;
            sqlString = sqlString + " where " + keyField + "=@" + this.keyField;
            sqlDataItem.CommandText = sqlString;
        }

        public OperatorInstanceEntity GetOperatorInstanceEntity(DataRow dr)
        {
            OperatorInstanceEntity entity = new OperatorInstanceEntity();
            string value = "";
            entity.OperatorInstanceId = dr["OperatorInstanceId"].ToString();
            entity.WorkFlowId = dr["WorkFlowId"].ToString();
            entity.WorkTaskId = dr["WorkTaskId"].ToString();
            entity.WorkFlowInstanceId = dr["WorkFlowInstanceId"].ToString();
            entity.WorkTaskInstanceId = dr["WorkTaskInstanceId"].ToString();
            entity.UserId = dr["UserId"].ToString();
            value = dr["OperType"].ToString();
            if (string.IsNullOrEmpty(value) == false)
            {
                entity.OperType = Convert.ToInt32(value);
            }
            value = dr["OperRealtion"].ToString();
            if (string.IsNullOrEmpty(value) == false)
            {
                entity.OperRealtion = Convert.ToInt32(value);
            }
            entity.OperContent = dr["OperContent"].ToString();
            entity.OperContentText = dr["OperContentText"].ToString();
            entity.OperStatus = dr["OperStatus"].ToString();
            value = dr["OperDateTime"].ToString();
            if (string.IsNullOrEmpty(value) == false)
            {
                entity.OperDateTime = Convert.ToDateTime(value);
            }
            entity.ChangeOperator = dr["ChangeOperator"].ToString();
            return entity;
        }

        #endregion

        #region  构造函数
        public OperatorInstance()
        { }
        public static OperatorInstance GetInstance()
        {
            return new OperatorInstance();
        }
        #endregion

        #region  公有方法
        #region  基本方法
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Insert(OperatorInstanceEntity entity)
        {
            try
            {
                setInsertSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Update(OperatorInstanceEntity entity)
        {
            try
            {
                setUpdateSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string operatorInstanceId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = tmpSql;
            sqlItem.AppendParameter("@" + keyField, operatorInstanceId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="operatorInstanceId">主键Id</param>
        /// <returns>影响的记录条数</returns>
        public void Delete(string operatorInstanceId)
        {
            try
            {
                string tmpSql = "delete from " + tableName + " where  " + keyField + "=@" + keyField;
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, operatorInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一条数据记录
        /// </summary>
        /// <param name="OperatorInstanceId">主键Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetOperatorInstanceTable(string operatorInstanceId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, operatorInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一个数据实体
        /// </summary>
        /// <param name="operatorInstanceId">主键Id</param>
        /// <returns>DataTable</returns>
        public OperatorInstanceEntity GetOperatorInstanceEntity(string operatorInstanceId)
        {
            DataTable dt = GetOperatorInstanceTable(operatorInstanceId);
            if (dt != null && dt.Rows.Count > 0)
            {
                return GetOperatorInstanceEntity(dt.Rows[0]);
            }
            return null;
        }

        #endregion

        #region  扩展方法
        //此处添加扩展方法

        /// <summary>
        /// 设定处理者实例正常结束
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="operatorInsId">处理者实例Id</param>
        public static void SetOperatorInstanceOver(string userId, string operatorInsId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_SetOperatorInstanceOverPro";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@UserId", userId);
                sqlItem.AppendParameter("@operatorInsId", operatorInsId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 设定处理者实例正常结束，不更新状态
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="operatorInsId">处理者实例Id</param>
        public static void SetOperatorInstance(string userId, string worktaskInsId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_SetOperatorInstanceOver";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@UserId", userId);
                sqlItem.AppendParameter("@worktaskInsId", worktaskInsId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public DataTable GetOperatorInstanceView(string operatorInstanceId)
        {
            string tmpSql = "select * from HF_WorkTaskInstanceView where operatorInstanceId=@operatorInstanceId" ;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@operatorInstanceId", operatorInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 判断处理者实例是否已存在，避免重复产生处理者实例，该方法针对与处理者策略是共享任务的情况
        /// </summary>
        /// <param name="workTaskInstanceId">任务模板Id</param>
        /// <param name="operContent">处理者Id</param>
        /// <param name="operType">处理者类型</param>
        /// <returns>是否存在</returns>
        public static bool IsExistsOperator(string workTaskInstanceId, string operContent)
        {
            string tmpSql = "select * from HF_OperatorInstance where operContent=@operContent and workTaskInstanceId=@workTaskInstanceId "
                           +"  and OperStatus=@OperStatus";
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@workTaskInstanceId", workTaskInstanceId);
                sqlItem.AppendParameter("@operContent", operContent);
               
                sqlItem.AppendParameter("@OperStatus", WorkFlowConst.OperStatus_0);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.RecordExists(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool IsLock(string worktaskid)
        {
            DataTable dt = GetWorktaskInsView(worktaskid);
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["OperContent"].ToString() =="" && dt.Rows[0]["TaskTypeId"].ToString() != "2")
                {
                    return false;
                }
            }
            return true;
        }
        public DataTable GetWorktaskInsView(string worktaskid)
        {
            string tmpSql = "select * from HF_WorkTaskInstanceView WHERE PreviousTaskInstanceId=@worktaskid and Status=1";
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@worktaskid", worktaskid);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public DataTable GetWorktaskInsStatus(string worktaskinsid)
        {
            string tmpSql = "select * from HF_WorkTaskInstanceView WHERE PreviousTaskInstanceId=@worktaskinsid";
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@worktaskinsid", worktaskinsid);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 判断处理者实例是否已存在，避免重复产生处理者实例，该方法针对与处理者策略是所有用户处理
        /// </summary>
        /// <param name="pWorkTaskInstanceId">前任务实例Id</param>
        /// <param name="workTaskId">当前任务模板Id</param>
        /// <param name="operContent">处理者Id</param>
        /// <param name="operType">处理者类型</param>
        /// <returns>是否存在</returns>
        public static bool IsExistsOperator(string pWorkTaskInstanceId,string workTaskId, string operContent, int operType)
        {
            string tmpSql = "select * from HF_WorkTaskInstanceView where operContent=@operContent and PreviousTaskInstanceId=@PTaskInstanceId "
                           + " and operType=@operType and OperStatus=@OperStatus";
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@PTaskInstanceId", pWorkTaskInstanceId);
                sqlItem.AppendParameter("@operContent", operContent);
                sqlItem.AppendParameter("@operType", WorkFlowConst.OperType_3, typeof(int));
                sqlItem.AppendParameter("@OperStatus", WorkFlowConst.OperStatus_0);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.RecordExists(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 判断指定流程任务节点是否有编辑字段
        /// </summary>
        /// <param name="WorkFlowId"></param>
        /// <param name="workTaskId"></param>
        /// <returns></returns>
        public static bool IsEditorWorkTaskFormValue(string WorkFlowId, string workTaskId)
        {
            string tmpSql = "select ID as listconvert from  HF_WorkTaskFormValue where WorkFlowId=@WorkFlowId and WorkTaskId=@workTaskId and State='editor'";

            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@WorkFlowId", WorkFlowId);
                sqlItem.AppendParameter("@workTaskId", workTaskId);
   
                ClientDBAgent agent = new ClientDBAgent();
                return agent.RecordExists(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        #endregion
        #endregion
    }
}

